package com.api.shopapi.controller;

import com.alibaba.fastjson.JSONObject;
import com.api.shopapi.entity.MyResult;
import com.api.shopapi.entity.PreCheck;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


@RestController
@RequestMapping("BaiduMap")
public class BaiduMapController extends BaseController{

    @RequestMapping(value = "Address", method = RequestMethod.POST)
    public MyResult Address(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String lat = jsonObject.getString("lat");
            String lon = jsonObject.getString("lon");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/BaiduMap/Address");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            JSONObject addr = geocodeAddr(lat, lon);

            return success(addr);

        } catch (Exception e) {
            insertError("/BaiduMap/Address", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }


    public static JSONObject geocodeAddr(String latitude, String longitude) {
        String url = String.format("http://api.map.baidu.com/reverse_geocoding/v3/?ak=g3NSlCzukWjUU3jWAGen4qluGZoEQvyz&output=json&coordtype=wgs84ll&location=%s,%s", latitude, longitude);
        URL myURL = null;
        JSONObject data = null;
        URLConnection httpsConn = null;
        try {
            myURL = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        }
        try {
            httpsConn = myURL.openConnection();
            if (httpsConn != null) {
                InputStreamReader insr = new InputStreamReader(httpsConn.getInputStream(), "UTF-8");
                BufferedReader br = new BufferedReader(insr);
                data = JSONObject.parseObject(br.readLine());
                insr.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return data;
    }

}
